import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from "@/utils/storage.js";
import useUserStore from "@/store/modules/user.js";
import store from "@/store/index.js";

const user = useUserStore(store)

NProgress.configure({
    easing: 'ease',  // 動畫方式，和css動畫屬性一樣（默認：ease）
    speed: 500,  // 遞增進度條的速度，單位ms（默認： 200）
    showSpinner: false,  // 是否顯示加載ico
    trickle: true,  //是否自動遞增
    height: 10,
    trickleSpeed: 200,  // 自動遞增間隔
    minimum: 0.3,   // 初始化時的最小百分比，0-1（默認：0.08）"
})
export const routes = [
    {
        path: '/',
        redirect: '/dashboard/analysis'
    },
    {
        name: 'login',
        path: '/login',
        meta: {
            title: '用户登录'
        },
        component: () => import('@/views/login/index.vue'),
    },
    {
        name: 'home',
        path: '/home',
        redirect: '/dashboard/analysis',
        component: () => import('@/views/home/index.vue'),
    },
    {
        name: 'bigdata',
        path: '/bigdata',
        component: () => import('@/views/bigdata/index.vue'),
    },
    {
        path: "/:pathMatch(.*)*",
        component: () => import('@/views/404/index.vue'),
        "hidden": true
    }
]
const router = createRouter({
    history: createWebHistory(),
    routes,
    //滚动行为
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { x: 0, y: 0 }
        }
    }
})

router.beforeEach(async (to, from, next) => {
    const token = getToken()
    document.title = (to.meta.title ? to.meta.title : '') + '·' + '履约系统'
    NProgress.start();
    if (token) {//判断token是否存在 存在即为已经登录
        if (user.init) { // 获取了动态路由 init一定true,就无需再次请求 直接放行
            next()
            NProgress.done();
        } else {
            // init为false,一定没有获取动态路由,就跳转到获取动态路由的方法
            const res = await user.GetPermissionList()
            const menuData = res.result.menu
            const accessRoutes = await user.generateRoutes(menuData)//解析路由,存储路由
            // 动态挂载路由
            await accessRoutes.forEach((route) => {
                router.addRoute(route.meta.layout, route)
            })
            user.init = true//init改为true,路由初始化完成
            next({ ...to, replace: true })// hack方法 确保addRoute已完成
            NProgress.done()
        }
    } else {
        if (import.meta.env.VITE_SSO == 'true') {
            setTimeout(() => {
                let service = window.location.protocol + '//' + window.location.host
                let path = window.location.search
                console.log(path)
                if (path.includes('?ticket')) {
                    path = path.split('?ticket')[0]
                } else if (path.includes('&ticket')) {
                    path = path.split('&ticket')[0]
                }
                window.location.href = import.meta.env.VITE_CAS_BASE_URL + '/login?service=' + service + window.location.pathname + path
            }, 500)
        } else {
            if (to.path === '/login') {
                next()
            } else {
                next({ path: '/login' })
                NProgress.done()
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
export default router
